package com.lantu.draw.login.action;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lantu.draw.login.MD5Encrypt;
import com.lantu.draw.login.service.LoginService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

//dispatcher
@Action(
		value="/login",
		results={
			@Result(name = "checkResult",type = "json", params = { "root", "replyMap" }),
			@Result(name = "login_fail",type = "json", params = { "root", "replyMap" }),
			@Result(name = "login_success",type = "json", params = { "root", "replyMap" }),
			@Result(name = "success",type = "json", params = { "root", "replyMap" }),
			@Result(name = "input",type = "json", params = { "root", "replyMap" })
		}
)
@Validations(requiredFields={
		@RequiredFieldValidator(type=ValidatorType.SIMPLE,fieldName="userid",message="用户名不能为空！！"),
		@RequiredFieldValidator(type=ValidatorType.SIMPLE,fieldName="password",message="密码不能为空！！"),
		@RequiredFieldValidator(type=ValidatorType.SIMPLE,fieldName="checkCode",message="验证码不能为空！！"),
    },stringLengthFields={
		//@StringLengthFieldValidator(fieldName="password",minLength="8",maxLength="20",message="密码的长度必须大于8小于20个字符"),
		@StringLengthFieldValidator(fieldName="checkCode",minLength="4",maxLength="4",message="验证码长度必须4个字符")
		
	}
)
public class LoginAction  extends ActionSupport{
	private final static Logger logger = LoggerFactory.getLogger(LoginAction.class);
	public static final int SUCCESS = 1;
	public static final int FAILURE = 0;
	
	private String userid;
	
	public String getUserid() {
		return userid;
	}
	public void setUserid(String userid) {
		this.userid = userid;
	}

	private String password;
	private String checkCode;
	public String getCheckCode() {
		return checkCode;
	}
	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	private int checkResult;//身份验证结果
	private Map<String, Object> replyMap=new HashMap<String, Object>();
	
	public String register(){
		HttpServletResponse res=(HttpServletResponse)ServletActionContext.getResponse();
		res.addHeader("Access-Control-Allow-Origin","http://lantudrawing.com");
		res.addHeader("Access-Control-Allow-Methods", "GET, POST");
		res.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
		res.setHeader("Access-Control-Allow-Credentials","true");
		//String md5pwd=MD5Encrypt.getEncrypt().encode(password);
		if(loginService.usrexists(userid)){
			replyMap.put("code", "0");
			replyMap.put("desc", "用户已经存在");
			return("login_success");
		}
		HttpSession session = ServletActionContext.getRequest().getSession();
		
		if(session.getAttribute("validationCode")!=null&&checkCode.equals((String)session.getAttribute("validationCode"))){
			session.setAttribute("validationCode",null);
			session.setAttribute("userid", userid);
			replyMap.put("code", "1");
			replyMap.put("desc", "success");
			replyMap.put("userId", userid);
			loginService.register(userid,password);
			return("login_success");
		}
		replyMap.clear();
		replyMap.put("code", "0");
		replyMap.put("desc", "验证码失败");
		return "login_success";
	}
	@SkipValidation
	public String loginout(){
		HttpServletResponse res=(HttpServletResponse)ServletActionContext.getResponse();
		res.addHeader("Access-Control-Allow-Origin","http://lantudrawing.com");
		res.addHeader("Access-Control-Allow-Methods", "GET, POST");
		res.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
		res.setHeader("Access-Control-Allow-Credentials","true");
		logger.info("登出，清除会话");
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.setAttribute("userId", "0");
		session.invalidate();
		replyMap.clear();
		replyMap.put("code", "1");
		replyMap.put("desc", "success");
		return "success";
	}

	public String checkAuth(){
		HttpServletResponse res=(HttpServletResponse)ServletActionContext.getResponse();
		res.addHeader("Access-Control-Allow-Origin","http://lantudrawing.com");
		//res.addHeader("Access-Control-Allow-Methods", "GET, POST");
		//res.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
		//res.setHeader("Access-Control-Allow-Credentials","true");
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		//String md5pwd=MD5Encrypt.getEncrypt().encode(password);
		if(session.getAttribute("validationCode")!=null&&checkCode.equals((String)session.getAttribute("validationCode"))){
			session.setAttribute("validationCode",null);
		}else{
			replyMap.put("code", "0");
			logger.error("sessionid="+session.getId()+",session-vcod="+(String)session.getAttribute("validationCode")+"?"+checkCode);
			replyMap.put("desc", "验证码失效");
			return "login_fail";
		}
		if(loginService.login(userid,password)){//login success
			session.setAttribute("userid", userid);
			replyMap.put("code", "1");
			replyMap.put("desc", "success");
			replyMap.put("userId", userid);
			return("login_success");
		}else{ //login fail
			replyMap.put("code", "0");
			replyMap.put("desc", "密码不正确");
			
			return "login_fail";
			
		}
	}
	public int getCheckResult() {
		return checkResult;
	}

	public void setCheckResult(int checkResult) {
		this.checkResult = checkResult;
	}

	
	

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	public Map<String, Object> getReplyMap() {
		return replyMap;
	}
	public void setReplyMap(Map<String, Object> replyMap) {
		this.replyMap = replyMap;
	}

	@Resource
	private LoginService loginService;
	
}
